#[cfg(unix)]
fn main() {
    use app_core::utils::common::generate_builder;
    use app_core::utils::logger;
    use serialport::SerialPort;
    use serialport::TTYPort;
    use std::io::{self, Read};

    let builder = generate_builder();
    let mut port = TTYPort::open(&builder).expect("unable to open");
    // println!("{:?}", port.name().unwrap());
    let mut serial_buf = Vec::new();
    loop {
        match port.bytes_to_read() {
            Ok(bytes) if bytes > 0 => {
                let mut temp_buf = vec![0; bytes.try_into().unwrap()];
                match port.read(temp_buf.as_mut_slice()) {
                    Ok(t) => {
                        serial_buf.extend_from_slice(&temp_buf[..t]);
                        // Check if the received bytes form a complete message
                        while let Some(index) = serial_buf.iter().position(|&b| b == b'\n') {
                            let message = String::from_utf8_lossy(&serial_buf[..index]);

                            logger::lgprint("Received", message.trim());
                            // Remove the processed message from the buffer
                            serial_buf.drain(..index + 1);
                        }
                    }
                    Err(ref e) if e.kind() == io::ErrorKind::TimedOut => (),
                    Err(e) => {
                        eprintln!("{:?}", e);
                        break;
                    }
                }
            }
            Ok(_) | Err(_) => (), // No data available or error, continue loop
        }
    }
}

#[cfg(not(unix))]
fn main() {}
